layui.use(['layer', 'form', 'element', 'admin'], function () {
    var $ = layui.jquery;
    var layer = layui.layer;
    var form = layui.form;
    var element = layui.element;
    var admin = layui.admin;

    /* 选择头像 */
    $('#userInfoHead').click(function () {
        admin.cropImg({
            imgSrc: $('#userInfoHead>img').attr('src'),
            onCrop: function (res) {
                $('#userInfoHead>img').attr('src', res);
                parent.layui.jquery('.layui-layout-admin>.layui-header .layui-nav img.layui-nav-img').attr('src', res);
            }
        });
    });

    /* 监听表单提交 */
    form.on('submit(userInfoSubmit)', function (data) {
       // layer.msg(JSON.stringify(data.field));
        $.ajax({
            url: basePath + "/admin/users/updateUserInfo",
            type:"post",
            data: data.field,
            async: false,
            contentType: 'application/x-www-form-urlencoded',
            beforeSend:function(xhr){
                xhr.setRequestHeader("token", auth.token);
            },
            success: function (sResponse) {
                if(sResponse.code=="00000"){
                     layer.msg('更新成功', {icon: 1});
                }else{
                    layer.msg(sResponse.msg, {icon: 2, anim: 6});
                }
            },
            error:function(a,b,c){
                layer.msg('更新失败【'+c+'】', {icon: 2, anim: 6});
            }
        });

        return false;
    });

    getUserInfo();

    // 获取用户信息
    function getUserInfo(){
        $.ajax({
            type: "get",
            url: basePath + '/admin/users/query/'+auth.username,
            dataType: "json",
            //这里是重点
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("token", auth.token);
            },
            success: function (data) {
                if(data.code=="00000"){
                    let user=data.data;
                    form.val('userInfoForm', user);
                    $("#header-admin").attr("src",user.avatar);
                    $("#nickName").html(user.nickname);
                    var mobile = user.mobile;
                    var reg=/(\d{3})\d{4}(\d{4})/;
                    var tel1 = mobile.replace(reg, "$1****$2")
                    $("#mobileId").html(tel1);
                    $("#emailId").html(user.email);
                    var roleArr=[];
                    var role = user.roles;
                    for(var k=0;k<role.length;k++){
                        roleArr.push(role[k].roleId);
                    }
                    getRoleName(roleArr.join(","));
                }
            },
            error:function(error){console.log(error);}
        });
    };

    // 获取角色名
    function getRoleName(roleIds){
        debugger;
        $.ajax({
            type: "get",
            url: basePath + '/admin/roles/getRoleName/'+roleIds,
            dataType: "json",
            //这里是重点
            beforeSend: function (XMLHttpRequest) {
                XMLHttpRequest.setRequestHeader("token", auth.token);
            },
            success: function (data) {
                if(data.code=="00000"){
                  let result = data.data;
                  let arr = [];
                     for(var j=0;j<result.length;j++){
                         arr.push(result[j].name);
                     }
                    $("#roleName").html(arr.join(","));
                }
            },
            error:function(error){console.log(error);}
        });
    }
});

//定义一个空的位置构造函数
function Location() {
};
//定义一个可以获得经纬度的方法
Location.prototype.getLocation = function (callback) {
    var options = {
        enableHighAccuracy: true,
        maximumAge: 1000
    };
    this.callback = Object.prototype.toString.call(callback) == "[object Function]" ?
        callback :
        function (address) {
            alert(address.province + address.city);
            console.log("getLocation(callbackFunction) 可获得定位信息对象");
        };
    var thisSelf = this;
    if (navigator.geolocation) {
        //浏览器支持geolocation
        navigator.geolocation.getCurrentPosition(function (position) {
            //经度
            var longitude = position.coords.longitude;
            //纬度
            var latitude = position.coords.latitude;
            thisSelf.loadMapApi(longitude, latitude);
        }, thisSelf.onError, options);
    } else {
        //浏览器不支持geolocation
        alert('您的浏览器不支持地理位置定位3333');
    }
};
//定义一个可以解析经纬度的方法，调用百度的api
Location.prototype.loadMapApi = function (longitude, latitude) {
    var thisSelf = this;
    var oHead = document.getElementsByTagName('HEAD').item(0);
    var oScript = document.createElement("script");
    oScript.type = "text/javascript";
    oScript.src = "http://api.map.baidu.com/getscript?v=2.0&amp;ak=23PaibIMnxjErAzRGc5dAjCZeOTQtr3l&amp;services=&amp;t=20140930184510";
    oHead.appendChild(oScript);
    oScript.onload = function (date) {
        var point = new BMap.Point(longitude, latitude);
        var gc = new BMap.Geocoder();
        gc.getLocation(point, function (rs) {
            var addComp = rs.addressComponents;
            thisSelf.callback(addComp);
        });
    }
};
//定义出现查询位置出现意外的方法
Location.prototype.onError = function (error) {
    switch (error.code) {
        case 1:
            alert("位置服务被拒绝");
            break;
        case 2:
            alert("暂时获取不到位置信息");
            break;
        case 3:
            alert("获取信息超时");
            break;
        case 4:
            alert("未知错误");
            break;
    }
};
//调用
var local = new Location();
local.getLocation(function (res) {
    var str = "";
    for (i in res) {
        str = res[i] + str;
    }
    //document.querySelector("p").innerHTML = str;
    document.getElementById("myAddress").innerHTML = str;
})
